package org.lyh.base.interceptor;

import org.lyh.base.util.Result;
import org.lyh.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component //非三层架构,spring创建对象,使用这个注解
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token = request.getHeader("token");
        //2.判断token
        if (token!=null){//不为空,才能从redis获取,判断是否有该token对应的用户信息
            Object obj = redisTemplate.opsForValue().get(token);
            //2.2 obj是否为null
            if (obj!=null){//用户信息存在
                //重新设置过期时间30分钟
                redisTemplate.opsForValue().set(token,(Logininfo)obj,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //跳转到登录页面 - 不能直接跳 - 给前端一个json信息，让前端去跳
        //告诉前端：我给你响应一个json格式的数据
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}");
        return false;
    }
}
